package com.redlight.base;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.*;

/**
 * Created by chao on 2019/1/11.
 */
@MappedJdbcTypes({JdbcType.BLOB})
public class ConvertBlobTypeHandler extends BaseTypeHandler<String> {
    private static final String DEFAULT_CHARSET = "utf-8";

    public ConvertBlobTypeHandler() {
    }

    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ByteArrayInputStream bis;
        try {
            bis = new ByteArrayInputStream(parameter.getBytes("utf-8"));
        } catch (UnsupportedEncodingException var7) {
            throw new RuntimeException("Blob Encoding Error!");
        }

        ps.setBinaryStream(i, bis, parameter.length());
    }

    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Blob blob = rs.getBlob(columnName);
        if(null != blob) {
            byte[] returnValue = blob.getBytes(1L, (int)blob.length());

            try {
                return new String(returnValue, "utf-8");
            } catch (UnsupportedEncodingException var6) {
                throw new RuntimeException("Blob Encoding Error!");
            }
        } else {
            return null;
        }
    }

    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Blob blob = cs.getBlob(columnIndex);
        if(null != blob) {
            byte[] returnValue = blob.getBytes(1L, (int)blob.length());

            try {
                return new String(returnValue, "utf-8");
            } catch (UnsupportedEncodingException var6) {
                throw new RuntimeException("Blob Encoding Error!");
            }
        } else {
            return null;
        }
    }

    public String getNullableResult(ResultSet arg0, int arg1) throws SQLException {
        return null;
    }
}
